package net.ibizsys.eclipse.studio.handler;

import java.util.ArrayList;
import java.util.List;

import net.ibizsys.eclipse.studio.data.IBizApp;
import net.ibizsys.eclipse.studio.data.Project;
import net.ibizsys.eclipse.studio.data.IBizSystem;
import net.ibizsys.eclipse.studio.data.LocalDataManager;
import net.ibizsys.eclipse.studio.data.ProjectType;
import net.ibizsys.eclipse.studio.i18n.I18n;
import net.ibizsys.eclipse.studio.vc.SystemVCManager;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

/**
 * 提交系统代码到SVN库
 * 
 * @author <a href='http://www.weibo.com/xjtoo' target='_blank'>Enmaai</a>
 */
public class CommitSystemHandler extends AbstractHandler
{
	public CommitSystemHandler()
	{
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException
	{
		final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);

		if (window != null)
		{
			IStructuredSelection selection = (IStructuredSelection) window.getSelectionService().getSelection();
			Object firstElement = selection.getFirstElement();
			if (firstElement instanceof IAdaptable)
			{
				IProject project = (IProject) ((IAdaptable) firstElement).getAdapter(IProject.class);

				if (project != null)
				{
					final IBizSystem system = LocalDataManager.manager().getSystem(project.getName());

					if (system == null)
					{
						MessageDialog.openError(window.getShell(), I18n.Error, I18n.SystemDataError);
						return null;
					}

					final List<Project> projects = new ArrayList<Project>();

					for (Project ibizProject : system.getProjects())
					{
						if (ibizProject.getType().value() > ProjectType.USR.value())
						{
							projects.add(ibizProject);
						}
					}

					for (IBizApp ibizApp : system.getApps())
					{
						for (Project ibizProject : ibizApp.getProjects())
						{
							if (ibizProject.getType().value() > ProjectType.USR.value())
							{
								projects.add(ibizProject);
							}
						}
					}

					new Thread()
					{
						@Override
						public void run()
						{
							SystemVCManager.commit(system, projects);
						}
					}.start();
				}
			}
		}
		return null;
	}
}